<?php
/*
邮件管理
*/
class MailController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;
	
	public function init() {
		$this->commonAction();	
	}
	
	public function indexAction(){
		try {
			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	public function opsendAction() {
		try {
			 if(! $this->isPost ()){
					throw new Exception ( '参数错误！' );
				}
			 $p=$this->_request->getPost();
		     //print_r($p);  exit;
			 
		  	$title='给园长的信'.date('Y-m-d');
		    //获取每个校区学生数
			
			$mailbody  ='<p style="text-align:center; font-size:12px;">来自云中校车，如果您的邮件不能正常显示,<a href="http://www.yunxiaoche.com/letters.php">请点击这里</a></p>';
		    $mailbody .="<div id=\"main\" class=\"content\"><div class=\"word\">
    <p>亲爱的：   <span style=\"color:#F00\">".$p['reciever']." </span>，您好！<br/>
    <br/>
    我们已经将花名册导入系统，所有用户账号已经生成，详细账号请看附件。<br/><br/>
    接下来的步骤如下：<br/>
    1）教师培训：幼儿园熟悉园长管理后台、教师助手客户端。<br/>
    2）安装调试：主要是智能考勤机，网络环境等。<br/>
    3）家长宣传：园区印刷易拉宝、至家长一封信。<br/>
    4）账号发放：所有账号已经生成。请参考附件。<br/>
    <br/>
    注意：所有需要的材料都在网盘中可以看到。<br/><br/>
    链接：<span style=\"color:#F00\"><a href=\" ".$p['address']." \">".$p['address']." </a></span><br/> 
    密码：<span style=\"color:#F00\">".$p['pwd']." </span><br/>
    <br/>
    </p>
    </div>
</div>";
			
			$data=array();
			$data['tomail']=$p['email'];
			$data['subject']=$title;
			$data['message']=$mailbody; 
			$data['mailtype']='HTML';
			$data['appid']=0;
			$data['addtime']=time();
			$data['name']=$p['address'].'和'.$p['pwd'];
			//print_r($data);exit;
			$result=$this->_dbAdapter->insert('mailqueue',$data);
		    $mailid=$this->_dbAdapter->lastInsertId(); 
			
			if($mailid){			 
				try{
					$this->send($data['tomail'],$data['subject'],$data['message'],$data['mailtype']);
					$res1=$this->_dbAdapter->update('mailqueue',array('issent'=>1,'senttime'=>time()),'mailid='.$mailid);
				} catch ( Exception $e ) {
					$failures=$e->getMessage ();
					$res2=$this->_dbAdapter->update('mailqueue',array('issent'=>2,'senttime'=>time(),'failures'=>$failures),'mailid='.$mailid);
				}
			}
			 
			    if($res1){
				   $this->feedback ( '成功', '注意', '/'.$this->controller.'/index', 'tip',3); 		 
				}else{
				   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
				}  
			
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}


	public function deleteAction(){
		try {
			$qdate=date('Ymd',strtotime('-1 week'));//一个月以前日期
			$del_result = $this->_dbAdapter->delete ( 'mailqueue', 'day<' . $qdate );
			if ($del_result ) {
				$this->feedback ( 'success', 'success', '/'.$this->controller, 'tip', 3 );
			}else{
				$this->feedback ( 'dataclear1', 'note', '/'.$this->controller, 'tip', 3 );
			}
			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}


	public function autoAction(){
		try {
/*			$sql="select variable,value from setting where variable like 'mail%'";   
			$mailseting=$this->_dbAdapter->fetchPairs($sql);
			list($lastday_daily,$lastday_weekly)=explode(',',$mailseting['mail_report_set']);
			
			//伊顿周报
			//$this->weeklyEtonkids($lastday_weekly,$mailseting['mail_report_weekly_etonkids']); 				
			//exit;
			
			//生成前日日报
			if(strtotime($lastday_daily)<strtotime(date('Y-m-d'))){
				//$lastday_daily_short=date('ymd' , strtotime($lastday_daily)); 
				
				//班级上线统计
				//$this->dailyClassOnline($lastday_daily_short,$mailseting['mail_report_daily']); 

				//家长每日上线统计
				//$this->dailyParentsOnline($lastday_daily_short,$mailseting['mail_report_daily']); 
				
				//照片每日统计
				//$yesterday='2014-01-22';
				//$this->dailyPhotoCount($lastday_daily,$mailseting['mail_report_daily']); 
				
				//$lastday_daily=date('Y-m-d');
			}
			
			//生成本周周报
			if(  $lastday_weekly!=date('Y-m-d') &&  date('w')==1){

				//班级上线统计
				//$this->weeklyClassOnline($lastday_weekly,$mailseting['mail_report_weekly']); 

				//家长上线统计
				//$this->weeklyParentsOnline($lastday_weekly,$mailseting['mail_report_weekly']); 
				
				//照片统计
				//$lastday_weekly='2014-01-22';
				//$this->weeklyPhotoCount($lastday_weekly,$mailseting['mail_report_weekly']); 				

				//伊顿周报
				//$this->weeklyEtonkids($lastday_weekly,$mailseting['mail_report_weekly_etonkids']); 				
				
				//$lastday_weekly=date('Y-m-d');
			}	
								
			//$this->_dbAdapter->update('setting',array('value'=>$lastday_daily.','.$lastday_weekly),'variable="mail_report_set"');	
			
*/			
			
			//自动发邮件
			if(date('G')>20 || date('G')<8){
				exit;
			}
			
			$time=time();
	  		$sql = 'select * from mailqueue where issent=0 and addtime<='.$time.' and failures="" order by level desc,mailid asc limit 1';
			$result = $this->_dbAdapter->fetchRow($sql); 
			
			//$result=array('tomail'=>'huangronghui@mac-top.mobi,demengqi@qq.com','subject'=>'测试了了','message'=>'<b>测试结果怎样了</b>','mailtype'=>'HTML','mailid'=>0);
/*			if($result){			 
				try{
					//$tomail=explode(',',$result['tomail']);
					$this->send($result['tomail'],$result['subject'],$result['message'],$result['mailtype']);
					$this->_dbAdapter->update('mailqueue',array('issent'=>1,'senttime'=>$time),'mailid='.$result['mailid']);
				} catch ( Exception $e ) {
					$result['failures']=$e->getMessage ();
					//$this->log(var_export($result, true));
					$this->_dbAdapter->update('mailqueue',array('issent'=>2,'senttime'=>$time,'failures'=>$result['failures']),'mailid='.$result['mailid']);
				}
			}
*/
			exit;
			
		} catch ( Exception $e ) {
			echo $e->getMessage ();exit;
		}
	} 
		
public 	function send($mailto,$mailtitle='',$mailbody='',$mailtype='HTML'){
		
			$mailtype       = "HTML"?"HTML":"TXT";//邮件格式（HTML/TXT）,TXT为文本邮件
	        /**
			* smtp的用户名和密码设置
			*/
			$config = array('auth' => 'login',
						'username' => 'service@yunxiaoche.com',
						'password' => 'guokr2014');
			$smtp_server = "smtp.exmail.qq.com";
			
            /**
			* 连接smtp服务器
			*/
            $transport = new Zend_Mail_Transport_Smtp($smtp_server, $config);
            /**
			* 邮件发送类的实例，使用gb2312编码
			*/
            $mail = new Zend_Mail("gbk");
			/**
			* 编码转换
			*/
			$mailbody_header="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
		<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\" /><title>$mailsubject</title>
		<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>
		<style type=\"text/css\">
		body{margin:0 auto;color:#666}
		#main{margin:0 auto;}
		.content{margin:0 auto;width:680px; height:660px; background:url(http://www.yunxiaoche.com/img/letter_bg.jpg) no-repeat;}
		.word{ padding:200px 0px 0px 150px;  font-size:12px;}
		</style>
		</head><body>";
		
			$mailbody_end='</body></html>';
			$mailbody=$mailbody_header.$mailbody.$mailbody_end;
			
			$mailbody = iconv ("UTF-8","gbk",$mailbody);
			$mailtitle = iconv ("UTF-8","gbk",$mailtitle);
			$from_name = iconv ("UTF-8","gbk",'云中校车');
			$from = iconv ("UTF-8","gbk",'service@yunxiaoche.com');

			$mail->setSubject($mailtitle);
			if($mailtype=='TXT')
				$mail->setBodyText($mailbody);
			else
				$mail->setBodyHtml($mailbody);
				
            $mail->setFrom($from,$from_name);
			/**
			* 收信人是数组
			*/
			$mailto=explode(',',str_replace('，',',',$mailto));
			$this->log(var_export($mailto,true));
            if (is_array($mailto)){
				 foreach($mailto as $key =>$value)
				     $mail->addTo(trim($value));
			}else{
			    $mail->addTo($mailto);
            }
			/**
			* 发送
			*/
			
            $mail->send($transport);
			
}
	
		
	  //班级上线统计
	private  function dailyClassOnline($day,$tomail){
		
			$title='[云中校车日报001] 班级上线统计 - '.$day;
		   $sql='select b.schoolname,b.classname from central.online_class a left join central.class b on a.classid=b.classid where a.groupid=1  and a.day = "'.$day.'"  order by a.schoolid,a.classid';  
			$result = $this->_dbAdapter->fetchAll ( $sql ); 
			
				
			$mailbody       ='';
			$mailbody .= '<div id="main"><h2><caption>'.$title.'</caption></h2>'; 
			$mailbody .= '<table><tr><th>学校名称</th><th>班级名称</th></tr>';
			if($result)
			foreach($result as $key => $value){
				$mailbody .= '<tr>';
				$mailbody .= '<td>'.$value['schoolname'].'</td><td>'.$value['classname'].'</td>';
				$mailbody .= '</tr>';
				}
			$mailbody .= '<tr><th>总计：</th><th colspan="2">'.count($result).'</th></tr>'; 
			$mailbody .= '</table>';
			$mailbody .= '<p> 注：0表示今天没有班级上线</p></div>';
			//$this->log($mailbody);
			
			
		  		$data=array();
				$data['tomail']=$tomail;
				$data['subject']=$title;
				$data['message']=$mailbody; 
				$data['mailtype']='HTML';
				$data['appid']=1;
				$data['addtime']=time();
				$result=$this->_dbAdapter->insert('mailqueue',$data);

			return 1;  
	   } 		

	  //家长上线统计
	private  function dailyParentsOnline($day,$tomail){
		  	$title='[云中校车日报002] 家长上线统计 - '.$day;
	       $sql='select (select schoolname from etonkids.school where schoolid=etonkids.student.schoolid) as schoolname,(select classname from etonkids.class where classid=etonkids.student.classid) as classname,cnname from etonkids.student where uid in (SELECT uid FROM central.`online_student` where  day ="'.$day.'" and groupid=1) order by schoolid';
			$result = $this->_dbAdapter->fetchAll ( $sql ); 
			
			$mailbody =''; 
			if($result){
				$mailbody .= '<div id="main"><h2><caption>'.$title.'</caption></h2>'; 
				$mailbody .= '<table><tr><th>学校名称</th><th>班级名称</th><th>学生名称</th></tr>';
				if($result)
					foreach($result as $key => $value){
						$mailbody .= '<tr>';
						$mailbody .= '<td>'.$value['schoolname'].'</td><td>'.$value['classname'].'</td><td>'.$value['cnname'].'</td>';
						$mailbody .= '</tr>';
					}
				$mailbody .= '<tr><th>总计：</th><th colspan="2">'.count($result).'</th></tr>'; 
				$mailbody .= '</table>';
				$mailbody .= '<p> 注：0表示今天没有家长上线</p></div>';
			}
			//$this->log($mailbody);
			
				$data=array();
				$data['tomail']=$tomail;
				$data['subject']=$title;
				$data['message']=$mailbody; 
				$data['mailtype']='HTML';
				$data['appid']=1;
				$data['addtime']=time();
				$result=$this->_dbAdapter->insert('mailqueue',$data);


			return $mailbody;  
	   } 
	   

//查看班级的照片情况
   private    function dailyPhotoCount($day,$tomail){	 
		  	$title='[云中校车日报003] 照片上传统计 - '.$day;
			$groupname_en='etonkids';
/*
		   $sql='select b.schoolname,a.classname,(select count(*) from etonkids.article_files where uid_class=a.uid and isdelete=0 and ischecked=1 and date(updatetime)="'.$day.'") as num,(select count(*) from etonkids.article_files where uid_class=a.uid and isdelete=1 and date(updatetime)="'.$day.'") as num1 from etonkids.class a
			left join etonkids.school b on a.schoolid=b.schoolid
			where b.city="北京" order by b.schoolid,num asc';
		   echo $sql;
			$result = $this->_dbAdapter->fetchAll ( $sql ); 
*/			
			$sql='select a.uid,b.schoolname,a.classname from '.$groupname_en.'.class a left join '.$groupname_en.'.school b on a.schoolid=b.schoolid where b.city="北京" order by b.schoolid,a.uid';
			$result = $this->_dbAdapter->fetchAssoc ( $sql ); 
			$sum=array('count'=>count($result),'allnum'=>0,'videonum'=>0,'picnum'=>0,'nochecknum'=>0,'deletenum'=>0,'worknum'=>0,);
			if($result){
				$sql='select uid_class,count(*) as allnum, count(case when ischecked=1 and fext="mp4" and isdelete=0 then "videonum" end) as videonum,
				count(case when ischecked=1 and fext<>"mp4" and isdelete=0 then "picnum" end) as picnum,
				count(case when ischecked=0 and isdelete=0 then "nochecknum" end) as nochecknum,
				count(case when isdelete=1 then "deletenum" end) as deletenum,
				count(case when isdelete=0 and mark=1 then "worknum" end) as worknum
				from '.$groupname_en.'.article_files where date(updatetime)="'.$day.'" group by uid_class';
				$file_count = $this->_dbAdapter->fetchAssoc ( $sql ); 
				if($file_count){
					foreach($file_count as $key => $value){
						if(in_array($key,array_keys($result))){
							$result[$key]['allnum']=$value['allnum']?$value['allnum']:'';
							$result[$key]['videonum']=$value['videonum']?$value['videonum']:'';
							$result[$key]['picnum']=$value['picnum']?$value['picnum']:'';
							$result[$key]['nochecknum']=$value['nochecknum']?$value['nochecknum']:'';
							$result[$key]['deletenum']=$value['deletenum']?$value['deletenum']:'';
							$result[$key]['worknum']=$value['worknum']?$value['worknum']:'';
							
							$sum['allnum'] +=$value['allnum'];
							$sum['videonum'] +=$value['videonum'];
							$sum['picnum'] +=$value['picnum'];
							$sum['nochecknum'] +=$value['nochecknum'];
							$sum['deletenum'] +=$value['deletenum'];
							$sum['worknum'] +=$value['worknum'];
						}
					}
				}
			}
			
			$mailbody       ='';
			$mailbody .= '<div id="main"><h2><caption>'.$title.'</caption></h2>'; 
			$mailbody .= '<table><tr><th>学校名称</th><th>班级名称</th><th>总数</th><th>已审核视频</th><th>已审核照片</th><th>未审核</th><th>已删除</th><th>加入作品集</th></tr>';
			if($result)
			foreach($result as $key => $value){
				$mailbody .= '<tr>';
				$mailbody .= '<td >'.$value['schoolname'].'</td><td>'.$value['classname'].'</td><td>'.$value['allnum'].'&nbsp;</td><td>'.$value['videonum'].'&nbsp;</td><td>'.$value['picnum'].'&nbsp;</td><td>'.$value['nochecknum'].'&nbsp;</td><td>'.$value['deletenum'].'&nbsp;</td><td>'.$value['worknum'].'&nbsp;</td>';
				$mailbody .= '</tr>';
				}
			$mailbody .= '<tr><th>总计：</th><td>'.$sum['count'].'</td><td>'.$sum['allnum'].'</td><td>'.$sum['videonum'].'</td><td>'.$sum['picnum'].'</td><td>'.$sum['nochecknum'].'</td><td>'.$sum['deletenum'].'</td><td>'.$sum['worknum'].'</td></tr>'; 
			$mailbody .= '</table>';
			$mailbody .= '<p>总数=已审核视频+已审核照片+未审核+已删除</p></div>';
			
			
				$data=array();
				$data['tomail']=$tomail;
				$data['subject']=$title;
				$data['message']=$mailbody; 
				$data['mailtype']='HTML';
				$data['appid']=1;
				$data['addtime']=time();
				$result=$this->_dbAdapter->insert('mailqueue',$data);
			
			return 1;  
	   } 



	  //班级上线统计
	private  function weeklyClassOnline($startday,$tomail){
			$yesterday=date('y-m-d ' , strtotime('-1 day'));
			if(!$startday)
				$startday=date('y-m-d ' , strtotime('-7 day'));
				
		  	$title='[云中校车周报001] 班级上线统计('.$startday .'~'.$yesterday.')';

			$groupname_en='etonkids';
			$sql='select a.uid,b.schoolname,a.classname from '.$groupname_en.'.class a left join '.$groupname_en.'.school b on a.schoolid=b.schoolid where b.city="北京" order by b.schoolid,a.uid;';
			//echo $sql;
			$result = $this->_dbAdapter->fetchAssoc ( $sql ); 
			
			$sum=array('count'=>count($result),'onlinenum'=>0);
			if($result){
	
				$sql='select DISTINCT uid,day from central.online_class where groupid=1 and day>="'.date('ymd',strtotime($startday)).'" and day<="'.date('ymd',strtotime($yesterday)).'" order by day' ;
				//echo $sql;
				$onlinelist = $this->_dbAdapter->fetchAssoc ( $sql ); 
				if($onlinelist){
					foreach($onlinelist as $key => $value){
						if(in_array($key,array_keys($result))){
							$result[$key]['isonline']=$value['day'];
							$sum['onlinenum'] ++;
						}
					}
				}

			}
			
//		   $sql='select b.schoolname,b.classname from central.online_class a left join central.class b on a.classid=b.classid where a.groupid=1  and a.day = "'.$day.'"  order by a.schoolid,a.classid';  
//			$result = $this->_dbAdapter->fetchAll ( $sql ); 
			
				
			$mailbody       ='';
			$mailbody .= '<div id="main"><h2><caption>'.$title.'</caption></h2>'; 
			$mailbody .= '<table><tr><th>学校名称</th><th>班级名称</th><th>本周登陆过</th></tr>';
			if($result)
			foreach($result as $key => $value){
				$mailbody .= '<tr>';
				$mailbody .= '<td>'.$value['schoolname'].'</td><td>'.$value['classname'].'</td><td>'.$value['isonline'].'&nbsp;</td>';
				$mailbody .= '</tr>';
				}
			$mailbody .= '<tr><th>总计：</th><th>'.$sum['count'].'</th><th>'.$sum['onlinenum'].'</th></tr>'; 
			$mailbody .= '</table>';
			$mailbody .= '<p> 注：0表示今天没有班级上线</p></div>';
			//$this->log($mailbody);
			
			
		  		$data=array();
				$data['tomail']=$tomail;
				$data['subject']=$title;
				$data['message']=$mailbody; 
				$data['mailtype']='HTML';
				$data['appid']=2;
				$data['addtime']=time();
				$result=$this->_dbAdapter->insert('mailqueue',$data);

			return 1;  
	   } 		

	  //家长上线统计
	private  function weeklyParentsOnline($startday,$tomail){

			$yesterday=date('y-m-d ' , strtotime('-1 day'));
			if(!$startday)
				$startday=date('y-m-d ' , strtotime('-7 day'));
		  	$title='[云中校车周报002] 家长上线统计('.$startday .'~'.$yesterday.')';
	      // $sql='select (select schoolname from etonkids.school where schoolid=etonkids.student.schoolid) as schoolname,(select classname from etonkids.class where classid=etonkids.student.classid) as classname,cnname from etonkids.student where uid in (SELECT uid FROM central.`online_student` where  day >="'.date('ymd',strtotime($startday)).'" 		    and day <="'.date('ymd',strtotime($yesterday)).'" and groupid=1) order by schoolid';
//			echo $sql;exit;

			$groupname_en='etonkids';
			$sql='select DISTINCT a.uid,b.schoolname,a.classname,(select count(*) from '.$groupname_en.'.student where class_uid=a.uid) as allnum from '.$groupname_en.'.class a left join '.$groupname_en.'.school b on a.schoolid=b.schoolid where b.city="北京" order by b.schoolid,a.uid';
			$result = $this->_dbAdapter->fetchAssoc ( $sql ); 
			
			$sum=array('count'=>count($result),'allnum'=>0,'onlinenum'=>0);
			if($result){
				foreach($result as $key => $value){
					$sum['allnum'] +=$value['allnum'];
				}

	
				$sql='select b.uid_class,count(*) as num from central.push_student_token a left join central.student_class b on a.uid=b.uid_student where uid in (select DISTINCT uid from central.online_student where groupid=1 and day>="'.date('ymd',strtotime($startday)).'" and day<="'.date('ymd',strtotime($yesterday)).'") group by b.uid_class' ;
				$studentlist = $this->_dbAdapter->fetchAssoc ( $sql ); 
				if($studentlist){
					foreach($studentlist as $key => $value){
						if(in_array($key,array_keys($result))){
							$result[$key]['onlinenum']=$value['num'];
							$sum['onlinenum'] +=$value['num'];
						}
					}
				}
				
				$mailbody =''; 
				$mailbody .= '<div id="main"><h2><caption>'.$title.'</caption></h2>'; 
				$mailbody .= '<table><tr><th>学校名称</th><th>班级名称</th><th>学生总数</th><th>本周上线数</th></tr>';
				if($result)
					foreach($result as $key => $value){
						$mailbody .= '<tr>';
						$mailbody .= '<td>'.$value['schoolname'].'</td><td>'.$value['classname'].'</td><td>'.$value['allnum'].'&nbsp;</td><td>'.$value['onlinenum'].'&nbsp;</td>';
						$mailbody .= '</tr>';
					}
				$mailbody .= '<tr><th>总计：</th><th>'.$sum['count'].'</th><th>'.$sum['allnum'].'</th><th>'.$sum['onlinenum'].'</th></tr>'; 
				$mailbody .= '</table>';
				$mailbody .= '<p> 注：0表示今天没有家长上线</p></div>';
			}
			//$this->log($mailbody);
			
				$data=array();
				$data['tomail']=$tomail;
				$data['subject']=$title;
				$data['message']=$mailbody; 
				$data['mailtype']='HTML';
				$data['appid']=2;
				$data['addtime']=time();
				$result=$this->_dbAdapter->insert('mailqueue',$data);


			return $mailbody;  
	   } 
	   

//查看班级的照片及食谱、课程表情况
   private function weeklyPhotoCount($startday,$tomail){	 
			$yesterday=date('y-m-d ' , strtotime('-1 day'));
			if(!$startday)
				$startday=date('y-m-d ' , strtotime('-7 day'));
			
		  	$title='[云中校车周报003] 照片上传及食谱、课程表统计('.$startday .'~'.$yesterday.')';
			$groupname_en='etonkids';
/*
		   $sql='select b.schoolname,a.classname,(select count(*) from etonkids.article_files where uid_class=a.uid and isdelete=0 and ischecked=1 and date(updatetime)="'.$day.'") as num,(select count(*) from etonkids.article_files where uid_class=a.uid and isdelete=1 and date(updatetime)="'.$day.'") as num1 from etonkids.class a
			left join etonkids.school b on a.schoolid=b.schoolid
			where b.city="北京" order by b.schoolid,num asc';
		   echo $sql;
			$result = $this->_dbAdapter->fetchAll ( $sql ); 
*/			
			
			$sql='select a.uid,b.schoolname,a.classname from '.$groupname_en.'.class a left join '.$groupname_en.'.school b on a.schoolid=b.schoolid where b.city="北京" order by b.schoolid,a.uid';
			$result = $this->_dbAdapter->fetchAssoc ( $sql ); 
			$sum=array('count'=>count($result),'allnum'=>0,'videonum'=>0,'picnum'=>0,'nochecknum'=>0,'deletenum'=>0,'worknum'=>0,);
			if($result){
				$sql='select uid_class,count(*) as allnum, count(case when ischecked=1 and fext="mp4" and isdelete=0 then "videonum" end) as videonum,
				count(case when ischecked=1 and fext<>"mp4" and isdelete=0 then "picnum" end) as picnum,
				count(case when ischecked=0 and isdelete=0 then "nochecknum" end) as nochecknum,
				count(case when isdelete=1 then "deletenum" end) as deletenum,
				count(case when isdelete=0 and mark=1 then "worknum" end) as worknum
				from '.$groupname_en.'.article_files where date(updatetime)>="'.$startday.'" and date(updatetime)<="'.$yesterday.'"  group by uid_class';
				
			    //echo $sql;
				$file_count = $this->_dbAdapter->fetchAssoc ( $sql ); 
				//print_r($file_count);exit;
				//食谱情况
				$sql="select a.uid,(select max(menu_day) from ".$groupname_en.".menu where schoolid=a.schoolid) as max_menu_day from ".$groupname_en.".class_school_v a where a.city='北京' ORDER BY a.schoolid asc";
				$menu=$this->_dbAdapter->fetchPairs ( $sql );
				
				// 课程表情况				
				$sql='SELECT c.uid,a.contentid,a.calendarid,b.classid from '.$groupname_en.'.schedule_content a LEFT JOIN '.$groupname_en.'.schedule_content_class b on a.contentid=b.contentid LEFT JOIN '.$groupname_en.'.class c on b.classid=c.classid where c.uid<>""';
				$schedule=$this->_dbAdapter->fetchAssoc ( $sql );
				
				//取校历
				$sql='select cid,start_date,end_date from '.$groupname_en.'.calendar ';
				$calendar=$this->_dbAdapter->fetchAssoc($sql);
				$date=date('Y-m-d');				
				foreach($schedule as $key=>$value){
					if($calendar[$value['calendarid']]['start_date'] <= $date && $date <= $calendar[$value['calendarid']]['end_date']){
						$schedule[$key]['intime']='是';
					}else{
						$schedule[$key]['intime']='否';
					}
				}
				
				
				if($file_count){
					foreach($file_count as $key => $value){
						if(in_array($key,array_keys($result))){
							$result[$key]['allnum']=$value['allnum']?$value['allnum']:'';
							$result[$key]['videonum']=$value['videonum']?$value['videonum']:'';
							$result[$key]['picnum']=$value['picnum']?$value['picnum']:'';
							$result[$key]['nochecknum']=$value['nochecknum']?$value['nochecknum']:'';
							$result[$key]['deletenum']=$value['deletenum']?$value['deletenum']:'';
							$result[$key]['worknum']=$value['worknum']?$value['worknum']:'';
							$result[$key]['menu']=$menu[$key]?$menu[$key]:'';
							$result[$key]['schedule']=$schedule[$key]['intime']?$schedule[$key]['intime']:'';
							
							$sum['allnum'] +=$value['allnum'];
							$sum['videonum'] +=$value['videonum'];
							$sum['picnum'] +=$value['picnum'];
							$sum['nochecknum'] +=$value['nochecknum'];
							$sum['deletenum'] +=$value['deletenum'];
							$sum['worknum'] +=$value['worknum'];
						}
					}
				}
				//print_r($result);exit;
			}
			
			$mailbody       ='';
			$mailbody .= '<div id="main"><h2><caption>'.$title.'</caption></h2>'; 
			$mailbody .= '<table><tr><th>学校名称</th><th>班级名称</th><th>总数</th><th>已审核视频</th><th>已审核照片</th><th>未审核</th><th>已删除</th><th>加入作品集</th><th>最新食谱日期</th><th>是否本学期课程表</th></tr>';
			if($result)
			foreach($result as $key => $value){
				$mailbody .= '<tr>';
				$mailbody .= '<td >'.$value['schoolname'].'</td><td>'.$value['classname'].'</td><td>'.$value['allnum'].'&nbsp;</td><td>'.$value['videonum'].'&nbsp;</td><td>'.$value['picnum'].'&nbsp;</td><td>'.$value['nochecknum'].'&nbsp;</td><td>'.$value['deletenum'].'&nbsp;</td><td>'.$value['worknum'].'&nbsp;</td><td>'.$value['menu'].'&nbsp;</td><td>'.$value['schedule'].'&nbsp;</td>';
				$mailbody .= '</tr>';
				}
			$mailbody .= '<tr><th>总计：</th><td>'.$sum['count'].'</td><td>'.$sum['allnum'].'</td><td>'.$sum['videonum'].'</td><td>'.$sum['picnum'].'</td><td>'.$sum['nochecknum'].'</td><td>'.$sum['deletenum'].'</td><td>'.$sum['worknum'].'</td><td></td><td></td></tr>'; 
			$mailbody .= '</table>';
			$mailbody .= '<p>总数=已审核视频+已审核照片+未审核+已删除</p></div>';
			
			
				$data=array();
				$data['tomail']=$tomail;
				$data['subject']=$title;
				$data['message']=$mailbody; 
				$data['mailtype']='HTML';
				$data['appid']=2;
				$data['addtime']=time();
				$result=$this->_dbAdapter->insert('mailqueue',$data);
			
			return 1;  
	   } 
//伊顿周报
   private function handsend($startday,$tomail){	 
			
			
			return 1;  
	   } 



//伊顿周报
   private function weeklyEtonkids($startday,$tomail){	 
			$yesterday=date('y-m-d ' , strtotime('-1 day'));
			if(!$startday)
				$startday=date('y-m-d ' , strtotime('-7 day'));
			
			//$yesterday='14-03-30';
			//$startday='14-03-24';
		  	$title='[云中校车周报] 使用情况统计('.$startday .'~'.$yesterday.')';
			$groupname_en='etonkids';
			
		    //获取每个校区学生数
			$sql='select a.schoolid,b.schoolname,count(a.uid) as num from student a LEFT JOIN school b on a.schoolid=b.schoolid where a.groupid=1 and a.uid<>0 and b.city="北京" and b.schoolid<>67 group by schoolid';
		    $studentnum=$this->_dbAdapter->fetchAssoc($sql);
			
			//总次数
			$sql='select schoolid,sum(usednum) as num from online_student where groupid=1 and day>="'.date('ymd',strtotime($startday)).'" and day<="'.date('ymd',strtotime($yesterday)).'" group by schoolid';
			$total_online = $this->_dbAdapter->fetchPairs ( $sql ); 
			
			//上线家长人数
			$sql='select schoolid,COUNT(DISTINCT(uid)) as num from online_student where groupid=1 and day>="'.date('ymd',strtotime($startday)).'" and day<="'.date('ymd',strtotime($yesterday)).'" group by schoolid';
			$parentsonline = $this->_dbAdapter->fetchPairs ( $sql ); 
			
			//活跃度
			
			
			//照片总数			
			$sql="select a.schoolid,count(case when a.ischecked=1 and a.fext<>'mp4' and a.isdelete=0 and a.articlekey<>'' then 'picnum' end) as picnum from article_files_class_v a LEFT JOIN school b on a.schoolid=b.schoolid where b.groupid=1 and b.city='北京' and a.updatetime>='".date('Y-m-d H:i:s',strtotime($startday))."' and updatetime<='".date('Y-m-d H:i:s',strtotime($yesterday))."' group by a.schoolid";
			$picnum = $this->_dbAdapter->fetchPairs ( $sql );
			 
			$sum=array('count'=>0,'stunum'=>0,'parentsonline'=>0,'total_online'=>0,'picnum'=>0,'avgonline'=>0,'avgpicnum'=>0);
			if($studentnum){
					foreach($studentnum as $key => $value){
						if(in_array($key,array_keys($studentnum))){
							$studentnum[$key]['total_online']=$total_online[$key]?$total_online[$key]:'';
							$studentnum[$key]['huoyuedu']=round($total_online[$key]/$parentsonline[$key],2)?round($total_online[$key]/$parentsonline[$key],2):'';
							$studentnum[$key]['parentsonline']=$parentsonline[$key]?$parentsonline[$key]:'';
							$studentnum[$key]['picnum']=$picnum[$key]?$picnum[$key]:'';
							$studentnum[$key]['avgonline']=round($parentsonline[$key]/$value['num']*100,1)?round($parentsonline[$key]/$value['num']*100,1):'';
							if($studentnum[$key]['avgonline']){
								$studentnum[$key]['avgonline'] .='%';
							}
							$studentnum[$key]['avgpicnum']=round($picnum[$key]/$value['num'],2)?round($picnum[$key]/$value['num'],2):'';
														
							$sum['stunum'] +=$value['num'];
							$sum['parentsonline'] +=$parentsonline[$key];
							$sum['total_online'] +=$total_online[$key];
							$sum['picnum'] +=$picnum[$key];
							$sum['avgpicnum'] +=$studentnum[$key]['avgpicnum'];
						}
					}
			}
			
			$mailbody  ='';
			//$mailbody .='本周特别报道：<br /><br />今天到远洋调查云中校车使用情况，才发现远洋的网络设置问题导致所有的教师的设备无法上网。然而，可爱可敬的老师们利用业余时间在家使用自己的网络上传照片。当我们在周五晚上进行系统维护时，原本以为没有人使用，却发现远洋的老师正在使用，立刻引起了她们的反应。正是她们无私的付出，辛勤的劳动，获得了极高的家长活跃度和良好的家长反馈。<br /><br />我代表云中校车的全体员工向你们致敬！谢谢你们，正是你们的支持给了我们继续前行的动力！<br /><br />杨凯<br/><br />';
			$mailbody .= '<div id="main" style="margin:0 auto; padding:0; text-align:center"><h2><caption>'.$title.'</caption></h2>'; 
			$mailbody .= '<table border="1" cellpadding="0" cellspacing="0" bordercolor="#000000" style="margin:0 auto; padding:0; text-align:center; margin-bottom:20px;" ><tr bgcolor="#3db8ff" height="40"><th width="250">学校名称</th><th width="150">学生总数</th><th width="150">每周家长上线总次数</th><th width="150">覆盖人数</th><th width="150">活跃度(人均周上线次数)</th><th width="150">照片总数</th><th width="150">人均照片数</th><th width="150">覆盖率</th></tr>';
			if($studentnum)
			foreach($studentnum as $key =>$value){
				$mailbody .= '<tr height="30">';
				$mailbody .= '<td >'.$value['schoolname'].'</td><td>'.$value['num'].'</td><td>'.$value['total_online'].'&nbsp;</td><td>'.$value['parentsonline'].'&nbsp;</td><td>'.$value['huoyuedu'].'&nbsp;</td><td>'.$value['picnum'].'&nbsp;</td><td>'.$value['avgpicnum'].'&nbsp;</td><td>'.$value['avgonline'].'&nbsp;</td>';
				$mailbody .= '</tr>';
			}
			$mailbody .='<tr height="30"><td>总计</td><td>'.$sum['stunum'].'</td><td>'.$sum['total_online'].'</td><td>'.$sum['parentsonline'].'</td><td>&nbsp;</td><td>'.$sum['picnum'].'</td><td>'.$sum['picnum'].'</td><td>&nbsp;</td></tr>';
			$mailbody .= '</table>';
			$mailbody .='<div style=" margin:0 auto;width:1100px;margin-left:30px; text-align:left">每周家长上线总次数=每周家长登录次数总和<br />覆盖人数=每周上线的家长数<br />活跃度=每周家长上线总次数/覆盖人数<br />照片总数=老师每周拍摄总数(备注：1张照片有10个孩子，拍摄照片数为1)<br />人均照片数=每周拍摄照片总数/总学生数<br />覆盖率=覆盖人数/总学生数</div>';
			$mailbody .='<div style=" margin:0 auto;width:1100px;"><hr />';
			$mailbody .='<p style="text-align:left; margin-top:30px; margin-left:30px;">欢迎您使用云中校车，再次感谢您一直以来对云中校车的支持，我们仍会持续改进，全心全意为您服务。<br />云中校车官方网址：www.yunxiaoche.com ——时刻关注孩子的成长，为老师和家长架起便捷沟通的桥梁。</p></div>';
			$mailbody .= '</div>';
			//echo $mailbody;exit;
			
			$data=array();
			$data['tomail']=$tomail;
			$data['subject']=$title;
			$data['message']=$mailbody; 
			$data['mailtype']='HTML';
			$data['appid']=2;
			$data['addtime']=time();
			$result=$this->_dbAdapter->insert('mailqueue',$data);
			
			return 1;  
	   } 


//生成曲线图

public function lineaAction() {
		try {
			
			 
			$yesterday=date('y-m-d ' , strtotime('-1 day'));
			if(!$startday)
				$startday=date('y-m-d ' , strtotime('-7 day'));
			
			$end_date=date('Y-m-d',strtotime($yesterday));
			$start_date=date('Y-m-d',strtotime($startday));
			
			$end_date='2014-03-23';
			$start_date='2014-03-16';
			$groupname_en='etonkids';
			
			
			
//生成flash的start --------------	
   
   //设置时间轴 
	//查询本班级的学生总数　　
	
			$xmlData="<chart palette='2' caption='".$start_date.'~'.$end_date."  学生人数统计图表' rotateNames='0' showValues='0' divLineDecimalPrecision='1' limitsDecimalPrecision='1' PYAxisName='学生人数' SYAxisName='数量'  formatNumberScale='0' >";	 
			$categories="<categories>";
	 		$starttime=strtotime($start_date);
	 		$endtime =strtotime($end_date); 
	  		$timearray=array();
	  		$timearray[]=date("Ymd",$starttime);  
	 	 
			$i=$starttime;
			do{
				$i=$i+86400;  
				$timearray[]=date("Ymd",$i);
			}while ($i<$endtime); 
			//print_r($timearray);exit; 
			 
			foreach($timearray as $key=>$value){
				$categories.="<category label='".$value."' />";
			}		 
			$categories.="</categories>";  

		    $xmlData=$xmlData.$categories; 
			$this->view->timearray=$timearray;
			
/*//上线总人数
    		$where_online=' and day>="'.date("ymd",strtotime($start_date)) .'" and day <="'.date("ymd",strtotime($end_date)).'"'; 
     		$sql='select  day,count(DISTINCT uid) as onlinenum from  online_student where groupid=1 '.$where_online.'  group by day';  
			//echo $sql;echo '<br />';
     		$onlinestudent=$this->_dbAdapter->fetchAssoc ( $sql );  
	   		$xmlData.="<dataset  parentYAxis='S' seriesName='上线总人数' seriesName='比例' >";  
	  		for($i=0;$i<count($timearray);$i++){
		  		$day= substr($timearray[$i],2);  
			 	//$onlinestudent[$day]['lv_online']=$onlinestudent[$day]['onlinenum'];
			  	$xmlData.="<set value='".$onlinestudent[$day]['onlinenum']."' />";
		    }
		  	$xmlData.="</dataset>"; 
*/

//登陆总次数
    		$where_online_all=' and day>="'.date("ymd",strtotime($start_date)) .'" and day <="'.date("ymd",strtotime($end_date)).'"'; 
			$sql='select day,sum(usednum) as onlinenum from online_student where groupid=1 '.$where_online_all.' group by day';
			//echo $sql;exit;
			$onlinestudent_all = $this->_dbAdapter->fetchAssoc ( $sql ); 
	   		$xmlData.="<dataset  parentYAxis='S' seriesName='登陆总次数' seriesName='比例' >";  
	  		for($i=0;$i<count($timearray);$i++){
		  		$day= substr($timearray[$i],2);  
			 	//$onlinestudent_all[$day]['lv_online']=$onlinestudent_all[$day]['onlinenum'];
			  	$xmlData.="<set value='".$onlinestudent_all[$day]['onlinenum']."' />";
		    }
		  	$xmlData.="</dataset>"; 
/*			
//活跃度
	   		$xmlData.="<dataset  parentYAxis='S' seriesName='活跃度' seriesName='比例' >";  
	  		for($i=0;$i<count($timearray);$i++){
		  		$day= substr($timearray[$i],2);  
			 	$onlinestudent_all[$day]['huoyuedu']=round($onlinestudent_all[$day]['onlinenum']/$onlinestudent[$day]['onlinenum'],0) ;
			  	$xmlData.="<set value='".$onlinestudent_all[$day]['huoyuedu']."' />";
		    }
		  	$xmlData.="</dataset>"; 
*///print_r($onlinestudent);echo '<br />';print_r($onlinestudent_all);exit;


//照片总数	
			$sql="select a.articlefilesid,a.updatetime from ".$groupname_en.".article_files_class_v a LEFT JOIN ".$groupname_en.".school b on a.schoolid=b.schoolid where b.city='北京' and a.ischecked=1 and a.fext<>'mp4' and a.isdelete=0 and a.articlekey<>'' and updatetime>='".date("Y-m-d H:i:s",strtotime($start_date))."' and updatetime<='".date("Y-m-d H:i:s",strtotime($end_date))."' ";
			$picture = $this->_dbAdapter->fetchAssoc ( $sql ); 
			$picnum=array();
			for($i=0;$i<count($timearray);$i++){
				$day= substr($timearray[$i],2);
				foreach($picture as $key=>$value){
					if(!isset($picnum[$day])){
						$picnum[$day]=0;
					}
					if($day==date('ymd',strtotime($value['updatetime']))){
						$picnum[$day]++;
					}
				}
			}
			//print_r($picnum);exit;
			
	   		$xmlData.="<dataset  parentYAxis='S' seriesName='发布图片数' seriesName='比例' >";  
	  		for($i=0;$i<count($timearray);$i++){
		  		$day= substr($timearray[$i],2);  
			  	$xmlData.="<set value='".$picnum[$day]."' />";
		    }
		  	$xmlData.="</dataset>"; 

			$xmlData.="</chart>";  
			$this->view->xmlData=$xmlData;
						
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	} 


//生成曲线图

public function lineAction() {
		try {
			$this->view->groupid=$groupid = ( int ) $this->_request->getParam ( 'groupid' );
			if(!$groupid){
				//跳转到机构列表
				throw new Exception ( '参数错误' );
			}
			//$sql='select groupname_en from groups where groupid='.$groupid;
			//$groupname_en=$this->_dbAdapter->fetchOne($sql);
			
			//显示校区列表
			$sql="SELECT schoolid,schoolname FROM school where groupid=1 and city='北京' and schoolid<>67  order by schoolid asc";
			$school=$this->_dbAdapter->fetchAssoc ( $sql );
			$this->view->school= $school; 
			
			
			//获取传参
			$schoolid = $this->_request->getParam ( 'schoolid' ); 
			$start_date = $this->_request->getParam ( 'start_date' ); 
			$end_date =  $this->_request->getParam ( 'end_date' );

			$this->view->schoolid=$schoolid;
			//时间段判断
			$now_date=date('Y-m-d');
			if(strtotime($start_date)<=0 || strtotime($start_date) > strtotime($now_date))
				$start_date=$now_date;
			if(!strtotime($end_date) || $end_date>$now_date)
				$end_date=$now_date;
			if($start_date>$end_date)
				$end_date=$start_date;
			$this->view->start_date=$start_date;
			$this->view->end_date=$end_date;
			//print_r($schoolid);exit;
			
			if($schoolid){
				//获取本校区学生数
				$sql='select count(a.uid) as num from student a LEFT JOIN school b on a.schoolid=b.schoolid where b.schoolid=1 and a.uid<>0 and b.city="北京" and b.schoolid='.$schoolid;
				$studentnum=$this->_dbAdapter->fetchOne($sql);
				//print_r($studentnum);exit;
				//获取周起始时间
				$weektimearray=$this->get_time_arr($start_date, $end_date, 'week');
				//print_r($arr);exit;
	/*Array ( [0] => Array ( [0] => 1393084800 [1] => 1393689599 ) [1] => Array ( [0] => 1393689600 [1] => 1394294399 ) [2] => Array ( [0] => 1394294400 [1] => 1394899199 ) [3] => Array ( [0] => 1394899200 [1] => 1395071999 ) ) */	
			
				$online_totalnum=array();
				$parentsonline=array();
				$huoyuedu=array();
				$fugailv=array();
				$picnum=array();
				foreach($weektimearray as $key=>$value){
					$start=date('ymd',$value[0]);
					$end=date('ymd',$value[1]);
					//登录总次数
					$sql="select sum(usednum) as num from online_student where day>='".$start."' and day<='".$end."' and groupid=1 and schoolid=".$schoolid;
					$online_totalnum=$this->_dbAdapter->fetchOne($sql);
					
					//上线家长人数
					$sql='select COUNT(DISTINCT(uid)) as num from online_student where groupid=1 and day>="'.$start.'" and day<="'.$end.'" and schoolid='.$schoolid;
					$parentsonline = $this->_dbAdapter->fetchOne ( $sql ); 
					
					//活跃度
					$huoyuedu[$start]=round($online_totalnum/$parentsonline,0);
					
					//覆盖率
					$fugai[$start]=round($parentsonline/$studentnum*100,0);
					if($fugai[$start])
						$fugailv[$start]=$fugai[$start] .'%';
					
					//人均照片和视频数 a.fext<>'mp4'
					$updatetime_start=date('Y-m-d H:i:s',$value[0]);
					$updatetime_end=date('Y-m-d H:i:s',$value[1]);
					$sql="select count(case when a.ischecked=1 and a.isdelete=0 and a.articlekey<>'' then 'picnum' end) as picnum from article_files_class_v a LEFT JOIN school b on a.schoolid=b.schoolid where b.groupid=1 and b.city='北京' and b.schoolid=".$schoolid." and a.updatetime>='".$updatetime_start."' and a.updatetime<='".$updatetime_end."' ";
					$picture = $this->_dbAdapter->fetchOne ( $sql );
					$picnum[$start]=round($picture/$studentnum,0);
				}				
			
				$this->view->huoyuedu=$huoyuedu;
				$this->view->fugailv=$fugailv;
				$this->view->picnum=$picnum;
	//生成flash的start --------------	
	   
	   //设置时间轴 
		//查询本班级的学生总数　　
		
				$xmlData="<chart palette='2' caption='".$start_date.'~'.$end_date."  云中校车使用情况统计图表' rotateNames='0' showValues='0' divLineDecimalPrecision='1' limitsDecimalPrecision='1' PYAxisName='云中校车使用情况' SYAxisName='数量'  formatNumberScale='0' >";	 
				$categories="<categories>";
				$starttime=strtotime($start_date);
				$endtime =strtotime($end_date); 
				$timearray=array();
				foreach($weektimearray as $key=>$value){
					$start=date('ymd',$value[0]);
					$end=date('ymd',$value[1]);
					$timearray[$start]=$start.'-'.$end;
				}
				 
				foreach($timearray as $key=>$value){
					$categories.="<category label='".$value."' />";
				}		 
				$categories.="</categories>";  
	
				$xmlData=$xmlData.$categories; 
				$this->view->timearray=$timearray;
	
	//照片总数			
				$xmlData.="<dataset  parentYAxis='S' seriesName='人均照片和视频数' seriesName='比例' >";  
				foreach($timearray as $key=>$value){
					if($picnum[$key])
						$xmlData.="<set value='".$picnum[$key]."' />";
					else
						$xmlData.="<set value='0' />";
				}
				$xmlData.="</dataset>"; 
	
	
	//活跃度
				$xmlData.="<dataset  parentYAxis='S' seriesName='活跃度' seriesName='比例' >";  
				foreach($timearray as $key=>$value){
					if($huoyuedu[$key])
						$xmlData.="<set value='".$huoyuedu[$key]."' />";
					else
						$xmlData.="<set value='0' />";
				}
				$xmlData.="</dataset>"; 
	
	//覆盖率			
				$xmlData.="<dataset  parentYAxis='S' seriesName='覆盖率' seriesName='比例' >";  
				foreach($timearray as $key=>$value){
					if($fugai[$key])
						$xmlData.="<set value='".$fugai[$key]."' />";
					else
						$xmlData.="<set value='0' />";
				}
				$xmlData.="</dataset>"; 
				
	
				$xmlData.="</chart>";  
				$this->view->xmlData=$xmlData;
		}	
					
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	} 

	private	function get_time_arr($s,$e,$m_or_w)
	{
		$arr=array();
		$start=strtotime($s." 00:00:00");
		$end=strtotime($e." 23:59:59");
		if($m_or_w=='week')
		{
			$s_w=date('w',$start);
			$f_w=7-$s_w;
		}else 
		{
			$allday=date('t',$start);
			$today=date('d',$start);
			$f_w=$allday-$today+1;
		}
		if($f_w){
				$f_end=$start+86400*$f_w-1;
			}else{
				$f_end=$start+86400-1;
			}
			$new_end=$f_end;
			if($end<$new_end){
				$arr[]=array($start,$end);
				return $arr;
			}
		while ($end>$new_end){
				$arr[]=array($start,$new_end);
				$start=$new_end+1;
				if($m_or_w=='week'){
					$day=7;
				}else {
					$day=date('t',$new_end+10);
				}
				$new_end=$new_end+$day*86400;
			}
			if($m_or_w=='week'){
				$fullday=7;
			}else{
			$fullday=date('t',$new_end);}
			$arr[]=array($new_end-$fullday*86400+1,$end);
			return $arr;
	}

	   		
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		
		throw new Exception ( 'Invalid method' );
		
		// all other methods throw an exception
		throw new Exception ( 'Invalid method "' . $method . '" called' );
	}

}

